/**
 *
 * Copyright 2016-present scrm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
import * as types from '../constants/ActionTypes';
const _ = require('lodash');

const initialState = {
  isRefreshing: false,
  memberList: [],
  loading: true
};

export default function member(state = initialState, action) {
  switch (action.type) {
    case types.FETCH_ALL_MEMBER_LIST:
      return Object.assign({}, state, {
        loading: action.loading
      })
    case types.RECEIVE_ALL_MEMBER_LIST: 
      return Object.assign({}, state, {
        loading: action.loading,
        memberList: state.memberList ? combine(state, action) : loadMore(state, action)
      });
    default:
      return state;
  }
}

function getMembers(memberList) {
  let members = [];
  _.map(memberList || [], (team, index) => {
    if (team.team_managers) {
      members = concatFilterDuplicate(members, team.team_managers)
    }

    if (team.team_members) {
      members = concatFilterDuplicate(members, team.team_members)
    }
  })
  return members;
}


function combine(state, action) {
  state.memberList = getMembers(action.memberList)
  return state.memberList;
}

function loadMore(state, action) {
  state.memberList = concatFilterDuplicate(
    state.memberList,
    getMembers(action.memberList)
  );
  return state.memberList;
}

function concatFilterDuplicate(list1, list2) {
  const set = new Set(list1.map(item => item.suid));
  const filterList2 = [];
  const length = list2.length;
  for (let i = 0; i < length; i++) {
    if (!set.has(list2[i].suid)) {
      filterList2.push(list2[i]);
    }
  }
  return list1.concat(filterList2);
}
